<?php

namespace Cyfy\Modules\Users;

use \Cyfy\Message;

class Module extends \Cyfy\Module
{
    /**
     * Which method the passwords are hashed. DO NOT CHANGE WHEN CYFY IS INSTALLED!
     * @see hash()
     */
    const HASH_ALGORITHM = 'md5';
    
    /**
     * Returns a hash of password.
     *
     * Uses hash algorithm, which you can set in constants of this page.
     * Hashes the password after appeding 'salt' from Cyfy class.
     *
     * @param string Password to hash.
     * @return string Hashed password.
     */
    static public function hashPassword($pw)
    {
        return hash(self :: HASH_ALGORITHM, $pw . \Cyfy\Cyfy ::  $passwordSalt);
    }
    
    /**
     * Administration interface.
     * @return string HTML output.
     */
    static function administration($name = "")
    {
        switch($name)
        {
            case "users":
                return Users :: administration();

            case "groups":
                return Groups :: administration();

            case "permissions":
                return Permissions :: administration();
                
            // interface
            case "":
                return array(
                    "users" => array("name" => self :: t(600), "description" => self :: t(630), "permission" => "see user list"),
                    "groups" => array("name" => self :: t(700), "description" => self :: t(710), "permission" => "groups and permissions"),
                    "permissions" => array("name" => self :: t(800), "description" => self :: t(810), "permission" => "groups and permissions")
                );
            default :
                return false;
        }
    }
    
    /**
     * Returns AJAX callback.
     */    
    static function ajax($name)
    {
        switch ($name)
        {
            case "adminGroupsList":
                return Groups :: ajaxList();
            
            case "adminGroupEdit":
                return Groups :: ajaxEdit($_POST["gid"]);

            case "adminGroupDelete":
                return Groups :: ajaxDelete($_POST["gid"]);
                
            case "userGroups":
                $user = \Cyfy\Modules\Users\User :: load($_POST["uid"]);
                return $user -> adminGetGroups();

            case "removeUserFromGroup":
                $user = \Cyfy\Modules\Users\User :: load($_POST["uid"]);
                
                // ok
                if($user && $user -> removeFromGroup($_POST["gid"]))
                {
                    \Cyfy\Message :: set(self :: t(7090));
                    return $user -> adminGetGroups();
                }
                \Cyfy\Message :: set(self :: t(7100), \Cyfy\Message :: ERROR);
                return false;                
            
            case "users":
                return Users :: ajaxUsers();

            case "savePermissions":
                return Permissions :: ajaxSave();
            
            case "deleteUser":
				return Users :: deleteUser($_POST["uid"]);            
                
            default:
                return false;
        }
    }

    /**
     * Gets the content
     * @return string HTML content
     */
    static function get($id)
    {
        switch ($id)
        {
            case "main":
                // user logged?
                if (Current :: $uid)
                {
                    \Cyfy\Template :: setTitle(self :: t(400));
                    return self :: main();
                }
                else
                {
                    \Cyfy\Message :: set(self :: t(140), \Cyfy\Message :: WARNING);
                    \Cyfy\Cyfy ::  redirectTo("user/login");
                    return false;
                }
                return;

            // register form
            case "register":
                \Cyfy\Template :: setTitle(self :: t(300));
                $form = new Forms\Register();
                $output = "<h2>" . self :: t(300) . "</h2>\n";
                $output .= $form->show();
                return $output;

            // registration finish
            case "register-success";
                return self :: registerSuccess();

            //login screen
            case "login":
            
                \Cyfy\Template :: setTitle(self :: t(100));
                $output = "<h2>" .self :: t(100) . "</h2>";
                // If user logged, show him the message.
                if (Current :: $uid != 0)
                {
                    \Cyfy\Message :: set(self :: t(101, array(Current :: $username)));
                }
                // Login form
                $form = new Forms\Login();
                $output .= $form->show();
                
                // If user can make new users -> show him the link
                if (\Cyfy\Cyfy ::  permission("Users", "register new users"))
                {
                    $output .= "<p>" . self::t(102, array("<a href=\"" . \Cyfy\Cyfy ::  getPath("user/register") . "\">", "</a>")) . "</p>";
                }
                // Recovery link
                if(\Cyfy\Modules :: isEnabled("PasswordRecovery"))
                {
                    $output .= "<p>" . self :: t(112, array("<a href=\"" . \Cyfy\Cyfy ::  getPath("user/password-recovery") . "\">", "</a>"))."</p>";
                }
                return $output;
                
            // logout
            case "logout":
                \Cyfy\Template :: setTitle(self :: t(200));
                return Current :: logout();

            // settings
            case "settings":
                \Cyfy\Template :: setTitle(self :: t(480));
                return Current :: settings();
                
            case "user-details":
                \Cyfy\Template :: setTitle(self :: t(400));
                return self :: userDetails(\Cyfy\Cyfy :: arg(1));
        }
    }

    /**
     * Blocks for the User module
     *
     * @param string Block ID
     * @return mixed String or array
     */
    static function blocks($name="")
    {
        if ($name != "")
        {
            // LOGIN FORM
            if ($name == "login-form")
            {
                $output = "";
                if (Current :: $uid == 0 || \Cyfy\Blocks :: $forcedShow)
                {
                    $form = new Forms\Login();
                    $output = "<h3><span>" . self :: t(110) . "</span></h3>\n";
                    $output .= $form->show();
                    if (\Cyfy\Cyfy ::  permission("Users", "register new users")) {
                        $output .= "<p><a href=\"" . \Cyfy\Cyfy ::  getPath('user/register')  ."\">" . self::t(950) . "</a></p>";
                    }
                 
                    if(\Cyfy\Modules :: isEnabled("PasswordRecovery"))
                    {
                        $output .= "<p><a href=\"" . \Cyfy\Cyfy ::  getPath('user/password-recovery')  ."\">" . self::t(940) . "</a></p>";
                    }
                }
                return $output;
            }
            // CURRENT USER
            if ($name == "current-user" && Current :: $uid != 0)
            {
                $output = "<h3 class=\"userInfoName\"><span><a href=\"" . \Cyfy\Cyfy ::  getPath("user/") . "\">" . Current :: $name . "</a></span></h3>\n";
                $output .= "<ul class=\"currentUserList\">\n";
                $output .= "  <li class=\"username\">" . self :: t(10) . ": <strong>" . Current :: $username . "</strong></li>\n";
                $output .= "  <li class=\"email\">" . self :: t(50) . ": <strong>" . Current :: $email . "</strong></li>\n";
                $output .= "  <li class=\"settings\"><a href=\"" . \Cyfy\Cyfy ::  getPath("user/settings") . "\">" . self :: t(930) . "</a></li>\n";
                $output .= "  <li class=\"logout\"><a href=\"" . \Cyfy\Cyfy ::  getPath("user/logout") . "\">" . self :: t(200) . "</a></li>\n";
                $output .= "</ul>\n";
                return $output;
            }
        }
        else
        {
            // LIST OF BLOCKS
            return array(
                "login-form" => self :: t(910),
                "current-user" => self :: t(920)
            );
        }
    }
    
    /**
     * Page shown to user after registration.
     * @todo Make this editable.
     */
    static function registerSuccess() {
        $output = "<h2>" . self :: t(1010) . "</h2>\n";
        $output .= "<p>" . self :: t(1020) . "</p>\n";
        $output .= "<p><strong><a href=\"" . \Cyfy\Cyfy ::  getPath("user/login") . "\">" . self::t(1030) . "</a></strong></p>";
        return $output;
    }

    
    /**
     * Method triggered when cyfy starts creating page.
     */    
    static public function start()
    {
        // IF SESSION WITH USER - LOAD IT
        if($_SESSION["userS"])
        {
           Current :: load($_SESSION["userS"]);
        }
        // loads permissions, even for anonymous
        Current :: loadPermissions();
    }
    
    /**
     * Method triggered when cyfy finishes creating page.
     */
    static public function end()
    {
        // stores information about current user
        Current :: saveSession();
    }
    
    /**
     * Main page shown after user logs in.
     * @return string HTML content.
     */
    static private function main()
    {
        // if WelcomeBox module available, show it
        if (\Cyfy\Modules :: isEnabled("WelcomeBox")) {
            return WelcomeBox :: show();
        }

        // returns own user info page
        $user = \Cyfy\Modules\Users\User :: load(Current :: $uid);
        return $user -> infoPage();
    }

    
    /**
     * User details
     * @param int UserID
     */
    static private function userDetails($uid)
    {
        // returns user info page
        $user = \Cyfy\Modules\Users\User :: load($uid);
        if(!$user)
        {
            return \Cyfy\Message::get(1120);
        }
        
        // title
        \Cyfy\Template :: setTitle(self :: t(1111, array($user -> name)));
        
        // return values
        return $user -> infoPage();
    }
}

